/*
 * Copyright 2022-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aurora.generator.core.worker.repository;

import lombok.RequiredArgsConstructor;
import org.aurora.generator.core.worker.entity.WorkerNodeEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * repository
 *
 * @author Evan Zhai
 * @since 1.0.0
 */
@Repository(value = "workerNodeRepository")
@RequiredArgsConstructor
public class WorkerNodeRepositoryImpl implements WorkerNodeRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkerNodeRepositoryImpl.class);

    final JdbcTemplate jdbcTemplate;

    @Override
    public WorkerNodeEntity getWorkerNodeByHostPort(String host, String port) {
        final String sql = "SELECT ID, HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED FROM WORKER_NODE WHERE HOST_NAME = ? AND PORT = ?";
        List<WorkerNodeEntity> list = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper<>(WorkerNodeEntity.class),
                host,
                port
        );
        LOGGER.info("query result size: {}", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void addWorkerNode(WorkerNodeEntity workerNode) {
        final String sql = " INSERT INTO WORKER_NODE(HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED) VALUES (?, ?, ?, ?, NOW(), NOW())";
        int result = jdbcTemplate.update(
                sql,
                workerNode.getHostName(),
                workerNode.getPort(),
                workerNode.getType(),
                workerNode.getLaunchDate()
        );
        if (result > 0) {
            LOGGER.info("Successfully added worker node!");
        }
    }

}
